var apply,apply_img,apply_link,apply_none,apply_video,apply_any,encodeURL;
(function($){
	"use strict";
	function returnWindowParent(){
		if (jQuery('#popup').val() == 1)
		{
			return window.opener;
		}
		else
		{
			return window.parent;
		}
	}
	function returnUrls(files){
		var path = jQuery('#cur_dir').val();
		path = path.replace('\\', '/');
		var base_url = jQuery('#base_url').val();
		var urls=[];
		var is_return_relative_url = jQuery('#return_relative_url').val();
		var is_ftp = jQuery('#ftp').val() == true;
		for(var i = 0; i< files.length; i++){
			var file = files[i];
			urls.push(encodeURL((is_return_relative_url == 1 ? path : base_url + path) + file));
		}
		return urls;
	}
	encodeURL = function(url)
	{
		var tmp = url.split('/');
		for (var i = 3; i < tmp.length; i++)
		{
			tmp[ i ] = encodeURIComponent(tmp[ i ]);
		}
		return tmp.join('/');
	}
	function handleFileLink($el)
	{
		var fun = $el.attr('data-function');
		if(fun=="apply_multiple"){
			$el.find('.selection:visible').trigger('click');
			$el.find('.selector:visible').trigger('click');
		}else{
			window[fun]($el.attr('data-file'), jQuery('#field_id').val(),$el);	
		}
	}
	jQuery('ul.grid').on('click','.link',function (e)
	{
		e.stopPropagation();
		handleFileLink(jQuery(this));
	});	
	apply = function(files, external)
	{
		var windowParent = returnWindowParent();
		var callback=jQuery('#callback').val();
		var fill = '';
		var ext_audio = ['ogg', 'mp3', 'wav'];
		var ext_video = ['mp4', 'ogg', 'webm'];

		if(!Array.isArray(files)){
			files = new Array(files);
		}
		var urls=returnUrls(files);

		var res = JSON.stringify(urls);
		if(urls.length==1){
			res = urls[0];
		}
		if (external != "")
		{
			if (jQuery('#crossdomain').val() == 1)
			{
				windowParent.postMessage({
						sender: 'responsivefilemanager',
						url: res,
						field_id: external
					},
					'*'
				);
			}
			else
			{
				var target = jQuery('#' + external, windowParent.document);
				
				target.val(res).trigger('change');
				if(callback==0)
				{
					if (typeof windowParent.responsive_filemanager_callback == 'function')
					{
						windowParent.responsive_filemanager_callback(external);
					}
				}else{
					if (typeof windowParent[callback] == 'function')
					{
					  windowParent[callback](external);
					}
				}
				close_window();
			}
		}
		else
		{
			for(var i = 0; i< urls.length; i++){

				var file = files[i];
				var alt_name = file.substr(0, file.lastIndexOf('.'));
				var ext = file.split('.').pop();
				ext = ext.toLowerCase();
				var url = urls[i];
				if ($.inArray(ext, ext_img) > -1)
				{
					if(jQuery('#add_time_to_img').val()){
						url = url + "?" + new Date().getTime();
					}
					fill += '<img src="' + url + '" alt="' + alt_name + '" /> ';
				}
				else
				{
					if ($.inArray(ext, ext_video) > -1)
					{
						fill += '<video controls source src="' + url + '" type="video/' + ext + '">' + alt_name + '</video> ';
					}
					else
					{
						if ($.inArray(ext, ext_audio) > -1)
						{
							if (ext == 'mp3')
							{
								ext = 'mpeg';
							}
							fill += '<audio controls src="' + url + '" type="audio/' + ext + '">' + alt_name + '</audio> ';
						}
						else
						{
							fill += '<a href="' + url + '" title="' + alt_name + '">' + alt_name + '</a> ';
						}
					}

				}
			}

			if (jQuery('#crossdomain').val() == 1)
			{
				windowParent.postMessage({
						sender: 'responsivefilemanager',
						url: res,
						field_id: null,
						html: fill
					},
					'*'
				);

			}
			else
			{
				// tinymce 3.X
				if (parent.tinymce.majorVersion < 4)
				{
					parent.tinymce.activeEditor.execCommand('mceInsertContent', false, fill);
					parent.tinymce.activeEditor.windowManager.close(parent.tinymce.activeEditor.windowManager.params.mce_window_id);
				}
				// tinymce 4.X
				else
				{
					parent.tinymce.activeEditor.insertContent(fill);
					parent.tinymce.activeEditor.windowManager.close();
				}
			}
		}
	}
	apply_img = function(files, external)
	{
		var windowParent = returnWindowParent();
		var callback=jQuery('#callback').val();
		if(!Array.isArray(files)){
			files = new Array(files);
		}
		var urls=returnUrls(files);

		var res = JSON.stringify(urls);
		if(urls.length==1){
			res = urls[0];
		}

		if (external != "")
		{
			if (jQuery('#crossdomain').val() == 1)
			{
				windowParent.postMessage({
						sender: 'responsivefilemanager',
						url: urls[0],
						field_id: external
					},
					'*'
				);
			}
			else
			{
				var target = jQuery('#' + external, windowParent.document);
				target.val(res).trigger('change');
				if(callback==0)
				{
					if (typeof windowParent.responsive_filemanager_callback == 'function')
					{
					  windowParent.responsive_filemanager_callback(external);
					}
				}else{
					if (typeof windowParent[callback] == 'function')
					{
					  windowParent[callback](external);
					}
				}
				close_window();
			}
		}
		else
		{
			if(jQuery('#add_time_to_img').val()){
				var url = urls[0] + "?" + new Date().getTime();
			}else{
				url = urls[0];
			}
			apply_any(url);
		}
	}

	apply_video = function(files, external)
	{
		var windowParent = returnWindowParent();
		var callback=jQuery('#callback').val();
		if(!Array.isArray(files)){
			files = new Array(files);
		}
		var urls=returnUrls(files);
		var res = JSON.stringify(urls);
		if(urls.length==1){
			res = urls[0];
		}

		if (external != "")
		{
			if (jQuery('#crossdomain').val() == 1)
			{
				windowParent.postMessage({
						sender: 'responsivefilemanager',
						url: urls[0],
						field_id: external
					},
					'*'
				);
			}
			else
			{
				var target = jQuery('#' + external, windowParent.document);
				target.val(res).trigger('change');
				if(callback==0)
				{
					if (typeof windowParent.responsive_filemanager_callback == 'function')
					{
					  windowParent.responsive_filemanager_callback(external);
					}
				}else{
					if (typeof windowParent[callback] == 'function')
					{
					  windowParent[callback](external);
					}
				}
				close_window();
			}
		}
		else
		{
			apply_any(urls[0]);
		}
	}

	apply_none = function(file, external,el)
	{
		console.log(el);
		var _this = el.parent().find('form a');
		_this[1].click();
		jQuery('.tip-right').tooltip('hide');
	}

	function getUrlParam(paramName)
	{
		var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i');
		var match = window.location.search.match(reParam);

		return ( match && match.length > 1 ) ? match[ 1 ] : null;
	}

	apply_any = function(url)
	{
		if (jQuery('#crossdomain').val() == 1)
		{
			window.parent.postMessage({
					sender: 'responsivefilemanager',
					url: url,
					field_id: null
				},
				'*'
			);
		}
		else
		{
			if (jQuery('#editor').val() === 'ckeditor') {
				var funcNum = getUrlParam('CKEditorFuncNum');
				window.opener.CKEDITOR.tools.callFunction(funcNum, url);
				window.close();
			} else {
				window.parent.postMessage({
					sender: 'responsivefilemanager',
					url: url,
					field_id: null
				}, window.location.origin);
				parent.tinymce.activeEditor.windowManager.close();
			}
		}
	}
	function close_window()
	{
		if (jQuery('#popup').val() == 1)
		{
			window.close();
		}
		else
		{
			if (typeof parent.jQuery(".modal:has(iframe)").modal == "function"){
				parent.jQuery(".modal:has(iframe)").modal("hide");
			}
			if (typeof parent.jQuery !== "undefined" && parent.jQuery)
			{
				if (typeof parent.jQuery.fancybox == 'object'){
					parent.jQuery.fancybox.getInstance().close();
				}
				else if(typeof parent.jQuery.fancybox == 'function'){
					parent.jQuery.fancybox.close();
				}
			}
			else
			{
				if(typeof parent.$.fancybox == 'function'){
					parent.$.fancybox.close();
				}
			}
		}
	}
})($);